﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LDCRNewEdit.Services;
using LDCRNewEdit.CustomCompent;
using LDCRNewEdit.Model;

namespace LDCRNewEdit.UI.游戏数据
{
    public partial class BaseDataForm : Form
    {
        public BaseDataForm()
        {
            InitializeComponent();
        }

        private void BaseDataForm_Load(object sender, EventArgs e)
        {
            foreach (string key in BaseDataService.BaseDataFormatList.Keys)
            {
                this.comboBox2.Items.Add(new ComboBoxItem(BaseDataService.BaseDataPathList[key].Name, BaseDataService.BaseDataPathList[key].ID));
            }

            this.comboBox2.SelectedIndex = 0;


            this.dataGridView1.ColumnHeadersVisible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //先清空
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Rows.Clear();

            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();
            this.comboBox1.Items.Clear();
            foreach (BaseData bd in BaseDataService.BaseDataList[key])
            {
                this.comboBox1.Items.Add(this.comboBox1.Items.Count + bd.Name);

            }
            if (this.comboBox1.Items.Count > 0)
                this.comboBox1.SelectedIndex = 0;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();
            BaseData personData = BaseDataService.BaseDataList[key][this.comboBox1.SelectedIndex];

            //先清空
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Rows.Clear();

            int rowcount = this.dataGridView1.Height / this.dataGridView1.RowTemplate.Height - 1;
            int colcount = personData.DataList.Count % rowcount == 0 ? personData.DataList.Count / rowcount : personData.DataList.Count / rowcount + 1;

            MyCheckBoxColumn myCbColumn = new MyCheckBoxColumn();
            myCbColumn.ReadOnly = false;
            myCbColumn.Width = 180;
            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            myCbColumn.DefaultCellStyle = style;

            for (int i = 0; i < colcount; i++)
            {
                this.dataGridView1.Columns.Add((MyCheckBoxColumn)myCbColumn.Clone());
            }

            int row = 0;
            int col = 0;
            object[] values = new object[colcount];
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = false;
            }
            foreach (BaseDataValue dataValue in personData.DataList)
            {
                if (col == 0)
                {
                    dataGridView1.Rows.Add(values);
                }
                SetDataGridValue(dataValue, row, col);
                row++;

                if (row == rowcount)
                {
                    row = 0;
                    col++;
                }
            }
        }

        private string padRightEx(string str, int totalByteCount)
        {
            Encoding coding = Encoding.GetEncoding("GBK");
            int dcount = 0;
            foreach (char ch in str.ToCharArray())
            {
                if (coding.GetByteCount(ch.ToString()) == 2)
                    dcount++;
            }
            string w = str.PadRight(totalByteCount - dcount);
            return w;
        }

        private void SetDataGridValue(BaseDataValue dataValue, int row, int column)
        {
            DataGridViewCell cell = dataGridView1.Rows[row].Cells[column];
            cell.ToolTipText = padRightEx(dataValue.Text, 14) + dataValue.Value;
            cell.Value = cell.Value != null && ((bool)cell.Value) == true;

            if (dataValue.IsString != 1)
            {
                try
                {
                    int index = int.Parse(dataValue.Value);

                    if (dataValue.Type >= 0 && index >= 0 && index < BaseDataService.BaseDataList[dataValue.Type.ToString()].Count)
                    {
                        cell.ToolTipText += BaseDataService.BaseDataList[dataValue.Type.ToString()][index].Name;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(string.Format("修改{0}数据失败，请设置为数字", dataValue.Text));
                }
            }
            
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();

            if (e.RowIndex + e.ColumnIndex * this.dataGridView1.Rows.Count >= BaseDataService.BaseDataList[key][this.comboBox1.SelectedIndex].DataList.Count)
            {
                return;
            }

            DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

            BaseDataValue dataValue = BaseDataService.BaseDataList[key][this.comboBox1.SelectedIndex].DataList[e.RowIndex + e.ColumnIndex * this.dataGridView1.Rows.Count];

            if (dataValue.Type >= 0)
            {
                InputTypeValueForm input = new InputTypeValueForm();
                dataValue.Value = input.show(dataValue.Value, dataValue.Type).Trim();
            }
            else
            {
                InputValueForm input = new InputValueForm();
                dataValue.Value = input.show(dataValue.Value).Trim();
            }
            SetDataGridValue(dataValue, e.RowIndex, e.ColumnIndex);

            //如果是名字，更新combo值
            if (dataValue.IsName == 1)
            {

                int index = this.comboBox1.SelectedIndex;
                this.comboBox1.Items[index] = index + dataValue.Value;

                BaseDataService.BaseDataList[key][index].Name = dataValue.Value;
            }

            this.dataGridView1.Update();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                BaseDataService.SaveBaseData();

                MessageBox.Show("保存成功", "提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败！" + ex.Message, "提示");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int index = this.comboBox1.SelectedIndex;
            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();

            if (index >= 0)         //复制当前的数据，并插入到下一行
            {
                BaseData baseData = (BaseData)BaseDataService.BaseDataList[key][index].Clone();

                BaseDataService.BaseDataList[key].Add(baseData);

                this.comboBox1.Items.Add(this.comboBox1.Items.Count + baseData.Name);
            }
            else    //如果没有记录，则新加入一个
            {
                BaseData baseData = new BaseData();
                List<BaseDataValue> list = new List<BaseDataValue>();

                for (int i = 0; i < BaseDataService.BaseDataFormatList[key].Count; )
                {
                    BaseDataFormat df = BaseDataService.BaseDataFormatList[key][i];
                    for (int j = 0; j < df.ArrayNum; j++)
                    {
                        BaseDataValue data = new BaseDataValue(df);
                        data.Value = "-1";

                        if (df.ArrayNum > 1)
                        {
                            data.Text = data.Text + (j + 1);
                        }

                        list.Add(data);

                        //如果有数组，则直接读取数组
                        for (int k = 1; k < df.GroupNum; k++)
                        {
                            data = new BaseDataValue(BaseDataService.BaseDataFormatList[key][i + k]);
                            data.Value = "-1";

                            if (df.ArrayNum > 1)
                            {
                                data.Text = data.Text + (j + 1);
                            }

                            list.Add(data);

                        }

                        if (data.IsName == 1)
                        {
                            baseData.Name = data.Value;
                        }

                    }
                    i += df.GroupNum;
                }

                baseData.DataList = list;

                BaseDataService.BaseDataList[key].Add(baseData);

                this.comboBox1.Items.Add(this.comboBox1.Items.Count + baseData.Name);
            }

            this.comboBox1.SelectedIndex = this.comboBox1.Items.Count - 1;
        }

        private void button4_Click(object sender, EventArgs e)
        {

            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();

            if (BaseDataService.BaseDataList[key].Count > 0)
            {
                BaseDataService.BaseDataList[key].RemoveAt(BaseDataService.BaseDataList[key].Count - 1);
            }
            else
            {
                return;
            }

            this.comboBox1.Items.RemoveAt(this.comboBox1.Items.Count - 1);

            if (this.comboBox1.SelectedIndex == -1 && this.comboBox1.Items.Count > 0)
            {
                this.comboBox1.SelectedIndex = this.comboBox1.Items.Count - 1;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*.xls|*.xls";
            ofd.FileName = key + ".xls";

            if (ofd.ShowDialog() == DialogResult.OK)
            {

                //BaseDataService.ImportFromExcel(key, ofd.FileName);

                comboBox2_SelectedIndexChanged(sender, e);

                MessageBox.Show("导入成功!");
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string key = ((ComboBoxItem)this.comboBox2.SelectedItem).Value.ToString();
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "*.xls|*.xls";
            sfd.FileName = key + ".xls";

            if (sfd.ShowDialog() == DialogResult.OK)
            {

                //BaseDataService.ExportToExcel(key, sfd.FileName);
                MessageBox.Show("导出成功!");
            }
        }
    }
}
